<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader :list="list" @addTask="addTaskFn"></TodoHeader>
    <TodoMain :list="showList" @del="delFn"></TodoMain>
    <TodoFooter
      @changeType="typeFn"
      :type="getsel"
      :len="showList.length"
      @clearTask="clearFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todolist')) || [],
      getsel: 'all', //all代表全部，yes代表已完成，no代表未完成
    }
  },
  computed: {
    showList() {
      if (this.getsel === 'yes') {
        return this.list.filter((item) => item.isDone)
      } else if (this.getsel === 'no') {
        return this.list.filter((item) => !item.isDone)
      } else {
        return this.list
      }
    },
  },
  methods: {
    addTaskFn(task) {
      // console.log('addTaskFn', task)
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: task,
        isDone: false,
      })
    },
    delFn(id) {
      // console.log(id)
      this.list = this.list.filter((item) => item.id !== id)
    },
    typeFn(type) {
      this.getsel = type
    },
    clearFn() {
      // console.log('清除已完成')
      this.list = this.list.filter((item) => !item.isDone)
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem('todolist', JSON.stringify(this.list))
      },
    },
  },
}
</script>
